package com.jhxy.algorithm.minstack;

import java.util.LinkedList;
import java.util.List;

/**
 * 最小栈_单栈法
 */
public class SingleStackSolution {

    List<Long> deltaStack;
    long minValue;

    public SingleStackSolution() {
        deltaStack = new LinkedList<>();
        minValue = Long.MAX_VALUE;
    }

    public void push(int val) {
        if (deltaStack.size() == 0) {
            minValue = val;
            deltaStack.add(0L);
        } else {
            //局部的差值
            long deltaValue = val - minValue;
            deltaStack.add(deltaValue);
            if (deltaValue < 0) {
                minValue += deltaValue;
            }
        }
    }

    public void pop() {
        long deltaValue = deltaStack.get(deltaStack.size() - 1);
        if (deltaValue < 0) {
            minValue -= deltaValue;
        }
    }

    public int top() {
        Long deltaValue = deltaStack.get(deltaStack.size() - 1);
        if (deltaValue < 0) {
            return Integer.parseInt(String.valueOf(minValue));
        } else {
            return Integer.parseInt(String.valueOf(minValue + deltaValue));
        }
    }

    public int getMin() {
        return Integer.parseInt(String.valueOf(minValue));
    }
}
